<template>
  <div class="createEdit-container">
    <div class="app-title-container title-position">
      <modules-title :title-name="types==1||requireId==''?'需求创建':'需求编辑'" style="margin-bottom: 20px">
        <template slot="btn">
          <el-button plain icon="el-icon-refresh-left" @click="goBack">返回</el-button>
          <!-- <el-button plain icon="el-icon-refresh" @click="resetForm">重置</el-button> -->
          <el-button type="primary" @click="saveForm">保存草稿</el-button>
          <el-button type="primary" @click="submitForm">提交评估</el-button>
        </template>
      </modules-title>
    </div>
    <div class="app-main-container main-content-container">
      <el-form ref="elForm" :model="formData" :rules="rules" size="small" label-width="120px">
        <el-row
          :gutter="15"
          class="form-row01"
          style="
            margin-left: 0px;
            margin-right: 0px;
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
          "
        >
          <el-form-item label="项目名称" prop="project_name" style="width: 50%">
            <el-input
              v-model="formData.project_name"
              placeholder="请输入项目名称"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="项目类型" prop="project_type_id" style="width: 50%">
            <el-select
              v-model="formData.project_type_id"
              placeholder="请选择项目类型"
              clearable
              :style="{ width: '100%' }"
              @change="projectTypeChange"
            >
              <el-option
                v-for="(item, index) in projectTypeOptions"
                :key="index"
                :label="item.dict_val"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="需求来源" prop="demand_source_id" style="width: 50%">
            <el-select
              v-model="formData.demand_source_id"
              placeholder="请选择需求来源"
              clearable
              :style="{ width: '100%' }"
              @change="demandSourceChange"
            >
              <el-option
                v-for="(item, index) in demandSourceOptions"
                :key="index"
                :label="item.dict_val"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="申报类别" prop="apply_type_id" style="width:50%">
            <el-select
              v-model="formData.apply_type_id"
              placeholder="请选择申报类别"
              clearable
              :style="{width: '100%'}"
              @change="applyTypeChange"
            >
              <el-option
                v-for="(item, index) in applyTypeOptions"
                :key="index"
                :label="item.dict_val"
                :value="item.id"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="优先级" prop="priority_id" style="width: 50%">
            <el-select
              v-model="formData.priority_id"
              placeholder="请选择项目优先级"
              clearable
              :style="{ width: '100%' }"
              @change="priorityChange"
            >
              <el-option
                v-for="(item, index) in priorityOptions"
                :key="index"
                :label="item.label"
                :value="item.value"
                :disabled="item.disabled"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="治疗领域" prop="treat_field" style="width: 50%">
            <el-input
              v-model="formData.treat_field"
              placeholder="请输入治疗领域"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="适应症" prop="indication" style="width: 50%">
            <el-input
              v-model="formData.indication"
              placeholder="请输入适应症"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="剂型与规格" prop="dosage_norms" style="width: 50%">
            <el-input
              v-model="formData.dosage_norms"
              placeholder="请输入剂型与规格"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="15" style="margin-left: 0px; margin-right: 0px">
          <el-form-item label="质量标准来源" prop="quality_source">
            <el-input
              v-model="formData.quality_source"
              placeholder="请输入质量标准来源"
              clearable
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="国内研发状态" prop="internal_research">
            <el-input
              v-model="formData.internal_research"
              type="textarea"
              placeholder="请输入国内研发状态"
              :autosize="{ minRows: 3, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="国外研发状态" prop="abroad_research">
            <el-input
              v-model="formData.abroad_research"
              type="textarea"
              placeholder="请输入国外研发状态"
              :autosize="{ minRows: 3, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="其他说明" prop="remark">
            <el-input
              v-model="formData.remark"
              type="textarea"
              placeholder="请输入其他说明"
              :autosize="{ minRows: 3, maxRows: 6 }"
              :style="{ width: '100%' }"
            />
          </el-form-item>
          <el-form-item label="附件">
            <!-- <upload ref="upload" :edit-list="fileList" :project-data="{project_id: 'require',validation: 1}"  @uploadSuccess="uploadSuccess" @deleteSuccess="deleteSuccess" /> -->
            <upload-select ref="upload" :edit-list="fileList" :project-data="{project_id: 'require',validation: 1}" @uploadSuccess="uploadSuccess" @deleteSuccess="deleteSuccess" />
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>
<script>
import {
  createRequire,
  updateRequire,
  requirementDetail,
  submitAudit
} from '@/api/requirement'
export default {
  data() {
    return {
      types: 1, // 1，创建，2，编辑，
      requireId: '',
      formData: {
        project_name: '',
        project_type: '',
        project_type_id: '',
        demand_source: '',
        demand_source_id: '',
        apply_type: '',
        apply_type_id: '',
        priority: '',
        priority_id: '',
        treat_field: '',
        indication: '',
        dosage_norms: '',
        quality_source: '',
        internal_research: '',
        abroad_research: '',
        remark: '',
        enclosure: []
      },
      fileList: [],
      rules: {
        project_name: [
          {
            required: true,
            message: '请输入项目名称',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        project_type_id: [
          {
            required: true,
            message: '请选择项目类型',
            trigger: 'change'
          }
        ],
        demand_source_id: [
          {
            required: true,
            message: '请选择需求来源',
            trigger: 'change'
          }
        ],
        apply_type_id: [
          {
            required: true,
            message: '请选择申报类别',
            trigger: 'change'
          }
        ],
        priority_id: [
          {
            required: true,
            message: '请选择优先级',
            trigger: 'change'
          }
        ],
        dosage_norms: [
          {
            required: true,
            message: '请输入规格与剂型',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        treat_field: [
          {
            required: true,
            message: '请输入治疗领域',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        indication: [
          {
            required: true,
            message: '请输入适应症',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        quality_source: [],
        internal_research: [
          {
            required: true,
            message: '请输入国内研发状态',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        abroad_research: [
          {
            required: true,
            message: '请输入国外研发状态',
            trigger: 'blur'
          },
          { pattern: '[^ \x22]+', message: '不能输入纯空格', trigger: 'blur' }
        ],
        remark: []
      },
      priorityOptions: [
        {
          label: '高',
          value: '1'
        },
        {
          label: '中',
          value: '2'
        },
        {
          label: '低',
          value: '3'
        }
      ],
      demandSourceOptions: [],
      projectTypeOptions: [],
      applyTypeOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    // 获取数据字典
    this.getSysAllDic()
    if (this.$route.query.types) {
      this.types = Number(this.$route.query.types)
    }
    this.requireId = this.$route.query.requireId
    if (this.types === 2) {
      this.getRequirementDetail(this.requireId)
    }
  },
  mounted() {},
  methods: {
    goBack() {
      this.refreshBack()
    },
    getSysAllDic() {
      let allDic = this.$store.getters.sysDic()
      if (!allDic) {
        this.$store.dispatch('sys/getSysAllDic').then(data => {
          allDic = data
        })
      }
      console.log(allDic)
      this.demandSourceOptions = allDic['demand_source']
      this.projectTypeOptions = allDic['project_type']
      this.applyTypeOptions = allDic['apply_type']
    },
    // 优先级改变
    priorityChange(val) {
      const obj = this.priorityOptions.find((itm) => {
        return itm.value === val
      })
      this.formData.priority = obj.label
    },
    // 项目来源选择改变
    demandSourceChange(val) {
      const obj = this.demandSourceOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.demand_source = obj.dict_val
      console.log(val, this.formData)
    },
    // 项目类型改变
    projectTypeChange(val) {
      const obj = this.projectTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.project_type = obj.dict_val
      console.log(val, this.formData)
    },
    // 申报类别改变
    applyTypeChange(val) {
      const obj = this.applyTypeOptions.find((itm) => {
        return itm.id === val
      })
      this.formData.apply_type = obj.dict_val
      console.log(val, this.formData)
    },
    // 附件删除成功
    deleteSuccess() {
      // this.formData.enclosure = this.$refs.upload.emitFileList()
    },
    // 附件上传成功
    uploadSuccess(file) {
      // this.formData.enclosure = this.$refs.upload.emitFileList()
    },
    submitForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        // TODO 提交表单
        this.$refs.upload.saveFile().then((dataList) => {
          this.formData.enclosure = dataList[0]
          this.submitManage()
        }).catch(err => {
          console.log(err)
        })
      })
    },
    // 直接提交---需要调保存接口（此处分创建和更新），成功后调提交审核接口
    async submitManage() {
      let createRes = null
      if (this.types === 1) {
        createRes = await createRequire(this.formData)
      } else {
        createRes = await updateRequire(this.formData)
      }
      const subRes = await submitAudit(createRes.data.id)
      if (subRes.code === 200) {
        this.$message({
          type: 'success',
          message: '提交成功',
          duration: 1500
        })
        this.refreshBack()
      }
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
      this.$refs['upload'].resetFileList()
    },
    // 保存草稿
    saveForm() {
      this.$refs['elForm'].validate((valid) => {
        if (!valid) return
        // TODO 提交表单
        this.$refs.upload.saveFile().then((dataList) => {
          this.formData.enclosure = dataList[0]
          console.log(this.formData,dataList)
          if (this.types === 1) {
            this.createRequireSubmit(this.formData)
          } else {
            this.updateRequireSubmit(this.formData)
          }
        }).catch(err => {
          console.log(err)
        })
      })
    },
    createRequireSubmit(datas) {
      createRequire(datas).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '创建成功',
            duration: 1500
          })
          this.types = 2
          this.getRequirementDetail(res.data.id)
          this.$router.replace({
            name: 'createRequirements',
            query: {
              types: 2,
              requireId: res.data.id
            }
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
            duration: 1500
          })
        }
      })
    },
    // 返回之后刷新列表
    refreshBack() {
      this.$route.params.refresh = true
      this.resetForm()
      this.$router.back()
    },
    updateRequireSubmit(datas) {
      updateRequire(datas).then((res) => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '修改成功',
            duration: 1500
          })
        } else {
          this.$message({
            type: 'error',
            message: res.msg,
            duration: 1500
          })
        }
      })
    },
    getRequirementDetail(id) {
      requirementDetail(id).then((res) => {
        if (res.code === 200) {
          this.formData = res.data
          this.fileList = res.data.enclosure
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
@import "@/assets/scss/views/requirements/createRequirement.scss";
</style>
